document.addEventListener('DOMContentLoaded', function() {
    const checkInDate = document.getElementById('checkInDate');
    const checkOutDate = document.getElementById('checkOutDate');
    const totalAmount = document.getElementById('totalAmount');
    const totalAmountInput = document.getElementById('totalAmountInput');
    const bookingForm = document.getElementById('bookingForm');
    const roomPrice = parseFloat(document.querySelector('input[name="roomPrice"]').value);
    
    // 获取上下文路径
    function getContextPath() {
        const path = window.location.pathname;
        const contextPath = path.substring(0, path.indexOf('/', 1));
        return contextPath || '';
    }
    
    // 设置最小日期为今天
    const today = new Date().toISOString().split('T')[0];
    checkInDate.min = today;
    checkOutDate.min = today;
    
    // 计算总金额
    function calculateTotal() {
        const checkIn = new Date(checkInDate.value);
        const checkOut = new Date(checkOutDate.value);
        
        if (checkInDate.value && checkOutDate.value && checkOut > checkIn) {
            const timeDiff = checkOut.getTime() - checkIn.getTime();
            const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
            const total = daysDiff * roomPrice;
            
            totalAmount.textContent = '¥' + total.toFixed(2);
            totalAmountInput.value = total.toFixed(2);
        } else {
            totalAmount.textContent = '¥0.00';
            totalAmountInput.value = '0';
        }
    }
    
    // 监听日期变化
    checkInDate.addEventListener('change', function() {
        checkOutDate.min = checkInDate.value;
        calculateTotal();
    });
    
    checkOutDate.addEventListener('change', calculateTotal);
    
    // 表单提交
    bookingForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const roomId = document.querySelector('input[name="roomId"]').value;
        const customerName = document.getElementById('customerName').value;
        const customerPhone = document.getElementById('customerPhone').value;
        const customerEmail = document.getElementById('customerEmail').value;
        const checkInDateValue = checkInDate.value;
        const checkOutDateValue = checkOutDate.value;
        const totalAmountValue = totalAmountInput.value;
        
        console.log('表单数据:', {
            roomId, customerName, customerPhone, customerEmail,
            checkInDateValue, checkOutDateValue, totalAmountValue
        });
        
        // 验证必填字段
        if (!customerName.trim()) {
            alert('请输入客户姓名！');
            return;
        }
        
        if (!customerPhone.trim()) {
            alert('请输入联系电话！');
            return;
        }
        
        if (!checkInDateValue) {
            alert('请选择入住日期！');
            return;
        }
        
        if (!checkOutDateValue) {
            alert('请选择退房日期！');
            return;
        }
        
        // 验证日期
        if (new Date(checkOutDateValue) <= new Date(checkInDateValue)) {
            alert('退房日期必须晚于入住日期！');
            return;
        }
        
        if (!totalAmountValue || totalAmountValue === '0') {
            alert('请选择有效的入住日期！');
            return;
        }
        
        // 构建请求URL
        const contextPath = getContextPath();
        const requestUrl = contextPath + '/hotel/book';
        console.log('请求URL:', requestUrl);
        
        // 构建请求参数
        const params = new URLSearchParams();
        params.append('roomId', roomId);
        params.append('customerName', customerName.trim());
        params.append('customerPhone', customerPhone.trim());
        params.append('customerEmail', customerEmail.trim());
        params.append('checkInDate', checkInDateValue);
        params.append('checkOutDate', checkOutDateValue);
        params.append('totalAmount', totalAmountValue);
        
        console.log('请求参数:', params.toString());
        
        // 显示加载状态
        const submitBtn = bookingForm.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = '预订中...';
        submitBtn.disabled = true;
        
        // 发送请求
        fetch(requestUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        })
        .then(response => {
            console.log('响应状态:', response.status);
            if (!response.ok) {
                throw new Error('网络请求失败: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('响应数据:', data);
            alert(data.message);
            if (data.success) {
                window.location.href = contextPath + '/hotel/bookings';
            }
        })
        .catch(error => {
            console.error('请求错误:', error);
            alert('预订失败，请重试！错误：' + error.message);
        })
        .finally(() => {
            // 恢复按钮状态
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        });
    });
});

// 张健钟修改booking.js代码